package ua.kharkov.photo.controllers;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import ua.kharkov.photo.dal.ImageRepository;
import ua.kharkov.photo.dal.UserRepository;
import ua.kharkov.photo.model.Image;
import ua.kharkov.photo.model.User;

@Controller
public class ImageController extends AbstractController {

	private UserRepository userRepository;
	private ImageRepository imageRepository;

	@Autowired
	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	@Autowired
	public void setImageRepository(ImageRepository imageRepository) {
		this.imageRepository = imageRepository;
	}

	@RequestMapping("/getImage/{id}")
	public void getImage(HttpServletResponse response,
			HttpServletRequest httpRequest, @PathVariable("id") final String id)
			throws IOException {
		response.setContentType("image/jpeg");

		Cookie[] cookies = httpRequest.getCookies();

		if (cookies == null || cookies[0].getValue().equals("")) {
			return;
		} else {
			for (User u : userRepository.getAllUsers()) {
				if (cookies[0].getValue().equals(
						DigestUtils.shaHex(u.getUserName() + u.getPassword()))) {
					List<Image> availableImagesForUser = imageRepository
							.getImagesbyUser(u);

					if (id.contains("th")) {
						for (Image image : availableImagesForUser) {
							if (id.replace("th", "").equals(
									Integer.toString(image.getId()))) {
								response.getOutputStream().write(
										image.getThumbnailData());
							}
						}
					} else {
						for (Image image : availableImagesForUser) {
							if (id.equals(Integer.toString(image.getId()))) {
								response.getOutputStream().write(
										image.getData());
							}
						}
					}
				}
			}
		}

		response.getOutputStream().flush();
	}
}
